package com.hmall.gateway.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.rsa.crypto.KeyStoreKeyFactory;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;

@Configuration
@EnableConfigurationProperties(JwtProperties.class)
public class SecurityConfig {

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Bean
    public KeyPair keyPair(JwtProperties properties){
        try {
            // 获取秘钥工厂
            KeyStoreKeyFactory keyStoreKeyFactory =
                    new KeyStoreKeyFactory(
                            properties.getLocation(),
                            properties.getPassword().toCharArray());
            //读取钥匙对
            return keyStoreKeyFactory.getKeyPair(
                    properties.getAlias(),
                    properties.getPassword().toCharArray());
        } catch (Exception e) {
            // 如果无法从密钥库加载密钥对，则生成临时密钥对用于开发环境
            try {
                KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
                generator.initialize(2048);
                return generator.generateKeyPair();
            } catch (NoSuchAlgorithmException ex) {
                throw new RuntimeException("无法生成备用密钥对", ex);
            }
        }
    }
}